package com.lottery.service.pc28.robotService;

import com.lottery.dto.Message;
import com.lottery.dto.MessageTube;
import com.lottery.entity.Bettinginfo;
import com.lottery.entity.RobotInfo;
import com.lottery.utils.AchieveDataUtil;
import com.lottery.utils.MessageTubes;
import com.lottery.utils.RandCodeUtil;
import com.lottery.utils.RobotParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RobotUserService {

	// public static Map<Integer, RobotInfo> robotOnlineUser = new
	// ConcurrentHashMap<Integer, RobotInfo>();
	public static ArrayList<RobotInfo> arrayRobotOnline = new ArrayList<RobotInfo>();
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	public void robotLogin() {
		// TODO Auto-generated method stub
		logger.debug("**********robotLogin***********");
		// robotOnlineUser.clear();
		arrayRobotOnline.clear();
		if (!RobotParams.bestart) {
			return;
		}
		if (RobotParams.robotinfo == null || RobotParams.robotinfo.size() == 0) {
			return;
		}
		if (RobotParams.robotBet == null || RobotParams.robotBet.size() == 0) {
			return;
		}
		// if (RobotParams.robotBetAmount == null ||
		// RobotParams.robotBetAmount.size()
		// == 0) {
		// return;
		// }
		int totalNum = RobotParams.robotinfo.size();
		int ac = RandCodeUtil.getRandNum(RobotParams.onlineNumMin, RobotParams.onlineNumMax);
		Set<Integer> indexs = new HashSet<Integer>();
		for (int i = 0; i < ac; i++) {
			indexs.add(RandCodeUtil.getRandNum(0, totalNum - 1));
		}

		for (int index : indexs) {
			RobotInfo robotInfo = RobotParams.robotinfo.get(index);
			int robotid = robotInfo.getRobotId();
			// robotOnlineUser.put(robotid, robotInfo);
			arrayRobotOnline.add(robotInfo);

			if (!RobotParams.robotSscBetting.containsKey(robotid)) {
				ArrayList<Bettinginfo> betList = new ArrayList<Bettinginfo>();
				RobotParams.robotSscBetting.put(robotid, betList);
			}

			if (!RobotParams.robotPc28Betting.containsKey(robotid)) {
				ArrayList<Bettinginfo> betList = new ArrayList<Bettinginfo>();
				RobotParams.robotPc28Betting.put(robotid, betList);
			}

			try {
				Thread.sleep(10);
			} catch (InterruptedException e) { // TODO Auto-generated catch
												// block
				e.printStackTrace();
			}

		}
		logger.debug("***************robotOnlineUser ::" + arrayRobotOnline.size());
	}

	public void robotLogout() {
		// TODO Auto-generated method stub
		logger.debug("**********robotLogout***********");
		// robotOnlineUser.clear();
		arrayRobotOnline.clear();
		// RobotParams.robotPc28Betting.clear();
		// RobotParams.robotSscBetting.clear();
	}

	public void playBetWay(String nextTime, String nextExpect, int lotteyType) {
		// robotLogin();
		logger.debug("***********playBetWay in***********");
		// if (lotteyType == 1) {
		// for (Entry<Integer, ArrayList<Bettinginfo>> entry :
		// RobotParams.robotSscBetting.entrySet()) {
		// entry.getValue().clear();
		// }
		// } else if (lotteyType == 2) {
		// for (Entry<Integer, ArrayList<Bettinginfo>> entry :
		// RobotParams.robotPc28Betting.entrySet()) {
		// entry.getValue().clear();
		// }
		// }
		if (arrayRobotOnline.size() == 0 || !RobotParams.bestart) {
			return;
		}
		try {
			Thread.sleep(30 * 1000); // 开始下注后，前30s不下注
		} catch (InterruptedException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		long inext = 0;
		try {
			inext = simpleDateFormat.parse(nextTime).getTime() / 1000;
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		ArrayList<String> typeList = RobotParams.robotBet;
		int betNum = RandCodeUtil.getRandNum((int) (RobotParams.activeNum * 0.5), (int) (RobotParams.activeNum * 1.5));
		int nextBet = 480000 / betNum; // 平均间隔时间，总时间按照8分钟来算
		int minNextBet = nextBet / 2;
		int maxNextBet = (int) (nextBet * 1.5);
		logger.debug("betNum -- nextBet : {} {}", betNum, nextBet);
		for (int i = 0; i < betNum; i++) {
			try {
				long cur = System.currentTimeMillis() / 1000;
				// 机器人停止下注,cur当前时间,inext下一期开奖时间
				if (inext - cur < 50) {
					logger.debug("*************** robot stop betting *********************");
					break;
				}
				logger.debug("*************** robot betting ***********************");
				int randnumber = RandCodeUtil.getRandNum(0, arrayRobotOnline.size() - 1);
				int robotID = arrayRobotOnline.get(randnumber).getRobotId();
				int betAmount = RandCodeUtil.getRandNum(RobotParams.robotBetMin, RobotParams.robotBetMax);
				betAmount = betAmount / 10 * 10;

				String betInfo = typeList.get(RandCodeUtil.getRandNum(0, typeList.size() - 1)) + betAmount;

				try {
					if (lotteyType == 1) {
						robotSscPlayWay(betInfo, robotID, nextExpect);
					} else if (lotteyType == 2) {
						robotPc28PlayWay(betInfo, robotID, nextExpect);
					}
					int sleeptime = RandCodeUtil.getRandNum(minNextBet, maxNextBet);
					logger.debug("*************** robot sleep {} ", sleeptime);
					Thread.sleep(sleeptime);

				} catch (Exception e) {
					e.printStackTrace();
					logger.error("robot bet error: ", e);
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("robot betting for error: ", e);
			}
		}
		logger.debug("***********robot playBetWay out***********");
	}

	private void robotSscPlayWay(String string, int userId, String nextExpect) {

		if (!RobotParams.robotinfoMap.containsKey(userId)) {
			return;
		}

		String param = "下注 " + string;
		logger.debug("****robotPlayWaySsc param参数:{},id参数:{}", param, userId);

		boolean flg = false;

		String[] array = param.split("\\s+");

		// 将array数组copy到strArray数组
		String[] strArray = copyArray(array);

		for (String str : strArray) {

			flg = false;

			// 截取所有的第一个字符串
			String one = "";
			String oneAfter = "";
			if (str.length() >= 1) {
				one = str.substring(0, 1);
				oneAfter = str.substring(1);
			}
			// 截取所有的前两个字符串
			String two = "";
			String twoAfter = "";
			if (str.length() >= 2) {
				two = str.substring(0, 2);
				twoAfter = str.substring(2);
			}

			// 大小单双玩法 下注单100 双100 大单100
			if (("大".equals(one) || "小".equals(one) || "单".equals(one) || "双".equals(one)) && isInteger(oneAfter)) {
				flg = true;
				Bettinginfo bettinginfo = new Bettinginfo();
				bettinginfo.setUserId(userId);
				bettinginfo.setPlaywayName("大小单双玩法");
				bettinginfo.setBettingrule(str);
				int bettingnumber = Integer.parseInt(oneAfter);
				bettinginfo.setBettingnumber(bettingnumber);
				bettinginfo.setExpect(nextExpect);
				bettinginfo.setState(2);
				Date date = new Date();
				bettinginfo.setBettingDate(date);
				bettinginfo.setPayDate(date);
				bettinginfo.setPlaywayinfoId(1);
				int eachMoney = 1;
				int bettingmoney = eachMoney * bettingnumber;
				bettinginfo.setBettingmoney(bettingmoney);
				RobotParams.robotSscBetting.get(userId).add(bettinginfo);
			} else if (("大单".equals(two) || "小单".equals(two) || "大双".equals(two) || "小双".equals(two))
					&& isInteger(twoAfter)) {
				flg = true;
				Bettinginfo bettinginfo = new Bettinginfo();
				bettinginfo.setUserId(userId);
				bettinginfo.setPlaywayName("大小单双玩法");
				bettinginfo.setBettingrule(str);
				int bettingnumber = Integer.parseInt(twoAfter);
				bettinginfo.setBettingnumber(bettingnumber);
				bettinginfo.setExpect(nextExpect);
				bettinginfo.setState(2);
				Date date = new Date();
				bettinginfo.setBettingDate(date);
				bettinginfo.setPayDate(date);
				bettinginfo.setPlaywayinfoId(1);
				int eachMoney = 1;
				int bettingmoney = eachMoney * bettingnumber;
				bettinginfo.setBettingmoney(bettingmoney);
				RobotParams.robotSscBetting.get(userId).add(bettinginfo);
			}

			// 猜合玩法 下注合100
			// 判断为合和是否为整数
			if ("合".equals(one) && isInteger(oneAfter)) {
				flg = true;
				Bettinginfo bettinginfo = new Bettinginfo();
				bettinginfo.setUserId(userId);
				bettinginfo.setPlaywayName("猜合");
				bettinginfo.setBettingrule(str);
				int bettingnumber = Integer.parseInt(oneAfter);
				bettinginfo.setBettingnumber(bettingnumber);
				bettinginfo.setExpect(nextExpect);
				bettinginfo.setState(2);
				Date date = new Date();
				bettinginfo.setBettingDate(date);
				bettinginfo.setPayDate(date);
				bettinginfo.setPlaywayinfoId(5);
				int eachMoney = 1;
				int bettingmoney = eachMoney * bettingnumber;
				bettinginfo.setBettingmoney(bettingmoney);
				RobotParams.robotSscBetting.get(userId).add(bettinginfo);
			}

			// 以"/"进行分割
			String[] s = str.split("/");

			// 数字玩法 下注1/100
			if (s.length == 2 && s[0].length() == 1 && isInteger(s[0]) && isInteger(s[1])) {
				flg = true;
				Bettinginfo bettinginfo = new Bettinginfo();
				bettinginfo.setUserId(userId);
				bettinginfo.setPlaywayName("数字玩法");
				bettinginfo.setBettingrule(str);
				int bettingnumber = Integer.parseInt(s[1]);
				bettinginfo.setBettingnumber(bettingnumber);
				bettinginfo.setExpect(nextExpect);
				bettinginfo.setState(2);
				Date date = new Date();
				bettinginfo.setBettingDate(date);
				bettinginfo.setPayDate(date);
				bettinginfo.setPlaywayinfoId(2);
				int eachMoney = 1;
				int bettingmoney = eachMoney * bettingnumber;
				bettinginfo.setBettingmoney(bettingmoney);
				RobotParams.robotSscBetting.get(userId).add(bettinginfo);
			}
			// 数字组合玩法 下注12/100 23/100 257/100
			if (s.length == 2 && s[0].length() > 1 && s[0].length() <= 5 && isInteger(s[0]) && isInteger(s[1])) {
				flg = true;
				Bettinginfo bettinginfo = new Bettinginfo();
				bettinginfo.setUserId(userId);
				bettinginfo.setPlaywayName("数字组合玩法");
				bettinginfo.setBettingrule(str);
				int bettingnumber = Integer.parseInt(s[1]);
				bettinginfo.setBettingnumber(bettingnumber);
				bettinginfo.setExpect(nextExpect);
				bettinginfo.setState(2);
				Date date = new Date();
				bettinginfo.setBettingDate(date);
				bettinginfo.setPayDate(date);
				bettinginfo.setPlaywayinfoId(3);
				int eachMoney = 1;
				int bettingmoney = eachMoney * bettingnumber;
				bettinginfo.setBettingmoney(bettingmoney);
				RobotParams.robotSscBetting.get(userId).add(bettinginfo);
			}
			// 数字定位玩法 下注1/2/100 2/3/100 2/5/100
			if (("1".equals(s[0]) || "2".equals(s[0]) || "3".equals(s[0]) || "4".equals(s[0]) || "5".equals(s[0]))
					&& (s.length == 3 && s[1].length() == 1 && isInteger(s[1]) && isInteger(s[2]))) {
				flg = true;
				Bettinginfo bettinginfo = new Bettinginfo();
				bettinginfo.setUserId(userId);
				bettinginfo.setPlaywayName("数字定位玩法");
				bettinginfo.setBettingrule(str);
				int bettingnumber = Integer.parseInt(s[2]);
				bettinginfo.setBettingnumber(bettingnumber);
				bettinginfo.setExpect(nextExpect);
				bettinginfo.setState(2);
				Date date = new Date();
				bettinginfo.setBettingDate(date);
				bettinginfo.setPayDate(date);
				bettinginfo.setPlaywayinfoId(4);
				int eachMoney = 1;
				int bettingmoney = eachMoney * bettingnumber;
				bettinginfo.setBettingmoney(bettingmoney);
				RobotParams.robotSscBetting.get(userId).add(bettinginfo);
			}
		}

		// 判断是否为true
		if (flg) {
			String robotBetInfo = AchieveDataUtil.robotDivision(string);
			String body = userId + "::" + RobotParams.robotinfoMap.get(userId).getRobotName() + "::"
					+ RobotParams.robotinfoMap.get(userId).getRobotPic() + "::" + robotBetInfo;
			Message message = new Message();
			message.setMessageBody(body);
			message.setType("0");
			message.setTimestamp(new Date().getTime());
			MessageTube messageTube = MessageTubes.getInstance().getSscBetMessageTube();
			int push = messageTube.push(message);
			logger.debug("return index={}, {},{},{}", messageTube.getHashCode(), push, message.getType(), body);

		}
	}

	private void robotPc28PlayWay(String string, int userId, String nextExpect) {

		if (!RobotParams.robotinfoMap.containsKey(userId)) {
			return;
		}

		String param = "下注 " + string;
		logger.debug("*****robotPlayWayPc28 param参数:{},id参数:{}", param, userId);

		boolean flg = false;

		String[] array = param.split("\\s+");

		// 将array数组copy到strArray数组
		String[] strArray = copyArray(array);

		for (String str : strArray) {

			flg = false;

			String one = "";
			String oneAfter = "";
			if (str.length() >= 1) {
				one = str.substring(0, 1);
				oneAfter = str.substring(1);
			}
			// 截取所有的前两个字符串
			String two = "";
			String twoAfter = "";
			if (str.length() >= 2) {
				two = str.substring(0, 2);
				twoAfter = str.substring(2);
			}
			// 单点玩法的切割
			String three = "";
			String threePlay = "";
			String threeAfter = "";
			if (str.length() >= 7) {
				three = str.substring(0, 2);
				threePlay = str.substring(3, 5);
				threeAfter = str.substring(6);
			}

			// 大小单双玩法 下注单100 双100 大单100
			if (("大".equals(one) || "小".equals(one) || "单".equals(one) || "双".equals(one)) && isInteger(oneAfter)) {
				flg = true;
				Bettinginfo bettinginfo = new Bettinginfo();
				bettinginfo.setUserId(userId);
				bettinginfo.setPlaywayName("大小单双玩法");
				bettinginfo.setBettingrule(str);
				int bettingnumber = Integer.parseInt(oneAfter);
				bettinginfo.setBettingnumber(bettingnumber);
				bettinginfo.setExpect(nextExpect);
				bettinginfo.setState(2);
				Date date = new Date();
				bettinginfo.setBettingDate(date);
				bettinginfo.setPayDate(date);
				bettinginfo.setPlaywayinfoId(1);
				int eachMoney = 1;
				int bettingmoney = eachMoney * bettingnumber;
				bettinginfo.setBettingmoney(bettingmoney);
				RobotParams.robotPc28Betting.get(userId).add(bettinginfo);
			} else if (("大单".equals(two) || "小单".equals(two) || "大双".equals(two) || "小双".equals(two))
					&& isInteger(twoAfter)) {
				flg = true;
				Bettinginfo bettinginfo = new Bettinginfo();
				bettinginfo.setUserId(userId);
				bettinginfo.setPlaywayName("大小单双玩法");
				bettinginfo.setBettingrule(str);
				int bettingnumber = Integer.parseInt(twoAfter);
				bettinginfo.setBettingnumber(bettingnumber);
				bettinginfo.setExpect(nextExpect);
				bettinginfo.setState(2);
				Date date = new Date();
				bettinginfo.setBettingDate(date);
				bettinginfo.setPayDate(date);
				bettinginfo.setPlaywayinfoId(1);
				int eachMoney = 1;
				int bettingmoney = eachMoney * bettingnumber;
				bettinginfo.setBettingmoney(bettingmoney);
				RobotParams.robotPc28Betting.get(userId).add(bettinginfo);
			}

			// 猜数字玩法
			if (("极大".equals(two) || "极小".equals(two) || "对子".equals(two) || "顺子".equals(two) || "豹子".equals(two))
					&& isInteger(twoAfter)) {
				flg = true;
				Bettinginfo bettinginfo = new Bettinginfo();
				bettinginfo.setUserId(userId);
				bettinginfo.setPlaywayName("猜数字玩法");
				bettinginfo.setBettingrule(str);
				int bettingnumber = Integer.parseInt(twoAfter);
				bettinginfo.setBettingnumber(bettingnumber);
				bettinginfo.setExpect(nextExpect);
				bettinginfo.setState(2);
				Date date = new Date();
				bettinginfo.setBettingDate(date);
				bettinginfo.setPayDate(date);
				bettinginfo.setPlaywayinfoId(1);
				int eachMoney = 1;
				int bettingmoney = eachMoney * bettingnumber;
				bettinginfo.setBettingmoney(bettingmoney);
				RobotParams.robotPc28Betting.get(userId).add(bettinginfo);

			}

			// 单点玩法,前段做验证,threePlay必须是两位数, 后台验证未加
			if ("单点".equals(three) && isInteger(threePlay) && isInteger(threeAfter)) {
				flg = true;
				Bettinginfo bettinginfo = new Bettinginfo();
				bettinginfo.setUserId(userId);
				bettinginfo.setPlaywayName("单点");
				bettinginfo.setBettingrule(str);
				int bettingnumber = Integer.parseInt(threeAfter);
				bettinginfo.setBettingnumber(bettingnumber);
				bettinginfo.setExpect(nextExpect);
				bettinginfo.setState(2);
				Date date = new Date();
				bettinginfo.setBettingDate(date);
				bettinginfo.setPayDate(date);
				bettinginfo.setPlaywayinfoId(1);
				int eachMoney = 1;
				int bettingmoney = eachMoney * bettingnumber;
				bettinginfo.setBettingmoney(bettingmoney);
				RobotParams.robotPc28Betting.get(userId).add(bettinginfo);
			}

		}

		// 判断是否为true
		if (flg) {
			String robotBetInfo = AchieveDataUtil.robotDivision(string);
			String body = userId + "::" + RobotParams.robotinfoMap.get(userId).getRobotName() + "::"
					+ RobotParams.robotinfoMap.get(userId).getRobotPic() + "::" + robotBetInfo;
			Message message = new Message();
			message.setMessageBody(body);
			message.setType("0");
			message.setTimestamp(new Date().getTime());
			MessageTube messageTube = MessageTubes.getInstance().getPc28BetMessageTube();
			int push = messageTube.push(message);
			logger.debug("return index={}, {},{},{}", messageTube.getHashCode(), push, message.getType(), body);

		}
	}

	private static String[] copyArray(String[] array) {

		String[] strArray = new String[(array.length) - 1];

		// 将array数组copy到strArray数组
		System.arraycopy(array, 1, strArray, 0, strArray.length);

		return strArray;

	}

	private static boolean isInteger(String str) {

		Pattern pattern = Pattern.compile("[0-9]+");
		Matcher matcher = pattern.matcher((CharSequence) str);

		return matcher.matches();

	}
}
